package com.klikmee.sms.core.base;

import java.util.Date;
import java.util.HashSet;

import com.klikmee.sms.core.base.dao.IncomingMessageFacadeLocal;
import com.klikmee.sms.core.base.dao.OutgoingMessageFacadeLocal;
import com.klikmee.sms.core.base.dao.PaymentInvoiceFacadeLocal;
import com.klikmee.sms.core.base.util.Constants;
import com.klikmee.sms.core.base.util.States;
import com.klikmee.sms.core.model.IncomingMessage;
import com.klikmee.sms.core.model.OutgoingMessage;
import com.klikmee.sms.core.model.PaymentInvoice;
import com.klikmee.sms.core.model.ServiceChargingCategory;

public class SimpleMessageCreatorImpl implements MessageCreator {

	private Core						core;
	private OutgoingMessageFacadeLocal	outgoingMessageDAO;
	private PaymentInvoiceFacadeLocal	paymentInvoiceDAO;

	public SimpleMessageCreatorImpl() {
	}

	public void setOutgoingMessageDAO( OutgoingMessageFacadeLocal outgoingMessageDAO ) {
		this.outgoingMessageDAO = outgoingMessageDAO;
	}

	public void setPaymentInvoiceDAO( PaymentInvoiceFacadeLocal paymentInvoiceDAO ) {
		this.paymentInvoiceDAO = paymentInvoiceDAO;
	}

	public void setCore( Core core ) {
		this.core = core;
	}

	public void init() {
	}

	/* (non-Javadoc)
	 * @see com.klikmee.sms.core.base.MessageCreator#createAndSendResponse(com.klikmee.sms.core.model.IncomingMessage, com.klikmee.sms.core.model.ServiceChargingCategory, java.lang.String)
	 */

	public Long createAndEnqueueResponse( IncomingMessage incomingMessage, ServiceChargingCategory charging, String responseText ) {

		// create response message
		OutgoingMessage outgoingMessage = OutgoingMessage.createFrom( incomingMessage );
		outgoingMessage.setMessage( responseText );
		outgoingMessage.setState( States.OutgoingMessage.WAITING_TO_BE_SENT );
		outgoingMessage.setTypeOfMessage( Constants.MESSAGE_TYPE_SMS );
		
		

		// create payment invoice
		PaymentInvoice paymentInvoice = new PaymentInvoice();

		paymentInvoice.setCreated( new Date() );
		paymentInvoice.setIncomingMessage( incomingMessage );
		paymentInvoice.setOutgoingMessage( outgoingMessage );
		paymentInvoice.setServiceChargingCategory( charging );
		paymentInvoice.setState( States.PaymentInvoice.WAITING_TO_BE_CHARGED );
		paymentInvoice.setType( Constants.PI_TYPE_CHARGED_MESSAGE );
		
		// add payment invoice to outgoing message
		outgoingMessage.setPaymentInvoiceList( new  HashSet<PaymentInvoice>());
		outgoingMessage.getPaymentInvoiceList().add( paymentInvoice );
		// create outgoing message
		outgoingMessageDAO.create( outgoingMessage );
		

		// enqueue message for sending
		core.enqueueOutgoingMessage( outgoingMessage );

		return outgoingMessage.getId();
	}
	
}
